package com.company.anr.controller;

import com.company.anr.config.AnrConfig;
import com.company.anr.model.AnalysisRequest;
import com.company.anr.model.AnalysisResponse;
import com.company.anr.service.AnrAnalysisService;
import com.company.anr.service.WebAutomationService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/analysis")
@CrossOrigin(origins = "*") // 允许跨域请求
public class AnalysisController {

  private static final Logger logger = LoggerFactory.getLogger(AnalysisController.class);

  @Autowired
  private AnrAnalysisService anrAnalysisService;

  @Autowired
  private WebAutomationService webAutomationService;

  @Autowired
  private AnrConfig anrConfig;

  /**
   * 分析设备日志
   * 
   * @param request 分析请求
   * @return 分析结果
   */
  @PostMapping("/device")
  public ResponseEntity<AnalysisResponse> analyzeDevice(@Valid @RequestBody AnalysisRequest request) {
    logger.info("收到分析请求: {}", request.getDeviceSn());

    try {
      AnalysisResponse response = anrAnalysisService.analyzeDevice(request);

      if (response.isSuccess()) {
        return ResponseEntity.ok(response);
      } else {
        return ResponseEntity.badRequest().body(response);
      }

    } catch (Exception e) {
      logger.error("处理分析请求时出错: {}", e.getMessage());
      AnalysisResponse errorResponse = new AnalysisResponse(false, "服务器内部错误: " + e.getMessage());
      return ResponseEntity.internalServerError().body(errorResponse);
    }
  }

  /**
   * 获取服务状态
   * 
   * @return 服务状态
   */
  @GetMapping("/status")
  public ResponseEntity<String> getStatus() {
    try {
      String status = anrAnalysisService.getServiceStatus();
      return ResponseEntity.ok(status);
    } catch (Exception e) {
      logger.error("获取服务状态时出错: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("服务状态获取失败");
    }
  }

  /**
   * 清理资源
   * 
   * @return 清理结果
   */
  @PostMapping("/cleanup")
  public ResponseEntity<String> cleanup() {
    try {
      anrAnalysisService.cleanup();
      return ResponseEntity.ok("资源清理完成");
    } catch (Exception e) {
      logger.error("清理资源时出错: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("资源清理失败");
    }
  }

  /**
   * 健康检查
   * 
   * @return 健康状态
   */
  @GetMapping("/health")
  public ResponseEntity<String> health() {
    return ResponseEntity.ok("ANR Analyzer Service is running");
  }

  /**
   * 初始化浏览器
   * 
   * @return 初始化结果
   */
  @PostMapping("/browser/init")
  public ResponseEntity<String> initializeBrowser() {
    try {
      logger.info("收到浏览器初始化请求");
      webAutomationService.initializeBrowser();
      return ResponseEntity.ok("浏览器初始化成功");
    } catch (Exception e) {
      logger.error("浏览器初始化失败: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("浏览器初始化失败: " + e.getMessage());
    }
  }

  /**
   * 执行完整的自动化工作流程
   * 
   * @param request 包含用户名、密码、设备SN和手机号的请求
   * @return 执行结果
   */
  @PostMapping("/automation/full")
  public ResponseEntity<String> executeFullAutomation(@RequestBody FullAutomationRequest request) {
    try {
      logger.info("收到完整自动化工作流程请求 - SN: {}, Phone: {}", request.getDeviceSn(), request.getPhone());

      String downloadedFile = webAutomationService.executeFullAutomationWorkflow(
          request.getUsername(),
          request.getPassword(),
          request.getDeviceSn(),
          request.getPhone());

      return ResponseEntity.ok("自动化工作流程执行成功，下载文件: " + downloadedFile);
    } catch (Exception e) {
      logger.error("完整自动化工作流程执行失败: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("自动化工作流程执行失败: " + e.getMessage());
    }
  }

  /**
   * 执行设备日志下载（适用于已登录的情况）
   * 
   * @param request 包含设备SN和手机号的请求
   * @return 执行结果
   */
  @PostMapping("/automation/download")
  public ResponseEntity<String> executeDeviceLogDownload(@RequestBody DeviceLogRequest request) {
    try {
      logger.info("收到设备日志下载请求 - SN: {}, Phone: {}", request.getDeviceSn(), request.getPhone());

      String downloadedFile = webAutomationService.executeDeviceLogDownload(
          request.getDeviceSn(),
          request.getPhone());

      return ResponseEntity.ok("设备日志下载成功，文件: " + downloadedFile);
    } catch (Exception e) {
      logger.error("设备日志下载失败: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("设备日志下载失败: " + e.getMessage());
    }
  }

  /**
   * 关闭浏览器
   * 
   * @return 关闭结果
   */
  @PostMapping("/browser/close")
  public ResponseEntity<String> closeBrowser() {
    try {
      logger.info("收到浏览器关闭请求");
      webAutomationService.closeBrowser();
      return ResponseEntity.ok("浏览器已关闭");
    } catch (Exception e) {
      logger.error("关闭浏览器失败: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("关闭浏览器失败: " + e.getMessage());
    }
  }

  /**
   * 调试下载按钮
   * 
   * @return 调试结果
   */
  @PostMapping("/debug/buttons")
  public ResponseEntity<String> debugDownloadButtons() {
    try {
      logger.info("收到调试下载按钮请求");
      webAutomationService.debugDownloadButtons();
      return ResponseEntity.ok("调试完成，请查看日志和截图");
    } catch (Exception e) {
      logger.error("调试下载按钮失败: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("调试失败: " + e.getMessage());
    }
  }

  /**
   * 处理已下载的文件 - 解压、重命名、解析ANR日志
   * 
   * @param request 包含设备SN的请求
   * @return 处理结果
   */
  @PostMapping("/process/downloaded")
  public ResponseEntity<String> processDownloadedFile(@RequestBody DeviceLogRequest request) {
    try {
      logger.info("收到处理已下载文件请求 - SN: {}", request.getDeviceSn());

      AnalysisResponse response = anrAnalysisService.processDownloadedFile(request.getDeviceSn());

      if (response.isSuccess()) {
        return ResponseEntity.ok("文件处理成功: " + response.getMessage());
      } else {
        return ResponseEntity.badRequest().body("文件处理失败: " + response.getMessage());
      }
    } catch (Exception e) {
      logger.error("处理已下载文件失败: {}", e.getMessage());
      return ResponseEntity.internalServerError().body("文件处理失败: " + e.getMessage());
    }
  }

  /**
   * 完整自动化请求模型
   */
  public static class FullAutomationRequest {
    private String username;
    private String password;
    private String deviceSn;
    private String phone;

    // Getters and Setters
    public String getUsername() {
      return username;
    }

    public void setUsername(String username) {
      this.username = username;
    }

    public String getPassword() {
      return password;
    }

    public void setPassword(String password) {
      this.password = password;
    }

    public String getDeviceSn() {
      return deviceSn;
    }

    public void setDeviceSn(String deviceSn) {
      this.deviceSn = deviceSn;
    }

    public String getPhone() {
      return phone;
    }

    public void setPhone(String phone) {
      this.phone = phone;
    }
  }

  /**
   * 设备日志请求模型
   */
  public static class DeviceLogRequest {
    private String deviceSn;
    private String phone;

    // Getters and Setters
    public String getDeviceSn() {
      return deviceSn;
    }

    public void setDeviceSn(String deviceSn) {
      this.deviceSn = deviceSn;
    }

    public String getPhone() {
      return phone;
    }

    public void setPhone(String phone) {
      this.phone = phone;
    }
  }

  /**
   * 调试配置信息
   */
  @GetMapping("/config/debug")
  public ResponseEntity<String> debugConfig() {
    try {
      StringBuilder configInfo = new StringBuilder();
      configInfo.append("=== 配置信息调试 ===\n");
      configInfo.append("工作目录: ").append(anrConfig.getWorkDirectory()).append("\n");
      configInfo.append("详细报告目录: ").append(anrConfig.getDetailDirectory()).append("\n");
      configInfo.append("处理后目录: ").append(anrConfig.getProcessedDirectory()).append("\n");
      configInfo.append("临时目录: ").append(anrConfig.getTempDirectory()).append("\n");
      configInfo.append("等待时间: ").append(anrConfig.getAutomationNotificationWaitSeconds()).append("秒\n");
      configInfo.append("==================");

      logger.info("配置调试信息: {}", configInfo.toString());
      return ResponseEntity.ok(configInfo.toString());
    } catch (Exception e) {
      logger.error("获取配置信息失败: {}", e.getMessage());
      return ResponseEntity.status(500).body("获取配置信息失败: " + e.getMessage());
    }
  }
}
